<template>
  <el-dialog
    v-model="visible"
    :close-on-click-modal="false"
    :title="title"
    :type="type"
    center
    width="48%"
    top="50px"
    class="group-dialog"
    @close="handleClose"
  >
    <div class="add-dialog-component">
      <el-alert
        :style="{ backgroundColor: '#fff' }"
        title="保存后将生效在移动端的分类里"
        type="info"
        :closable="false"
      />
      <el-tree
        ref="elTreeRef"
        class="tree-box"
        :data="treeData"
        :props="{ children: 'childs' }"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
      >
        <template #default="{ node, data }">
          <div class="custom-tree-node">
            <div class="content">
              <template v-if="data.depth < 3">
                <el-input
                  v-model="data.categoryName"
                  class="input"
                  :disabled="isCheck"
                  maxlength="6"
                  :placeholder="placeholderTips(data.depth)"
                />
                <el-upload
                  class="upload-uploader"
                  :on-success="handleImageSuccessOne"
                  :multiple="false"
                  :show-file-list="false"
                  :action="action"
                  :file-list="data.categoryImgArray"
                >
                  <img
                    v-if="
                      data.categoryImgArray.length &&
                        data.categoryImgArray[0].imgPath
                    "
                    width="80"
                    height="80"
                    :src="
                      data.categoryImgArray.length &&
                        data.categoryImgArray[0].imgPath
                    "
                  />
                  <el-icon v-else>
                    <el-icon-plus />
                  </el-icon>
                </el-upload>
              </template>
              <template v-else>
                <div
                  class="content"
                  :class="isCheck ? 'disabled' : ''"
                >
                  <el-input
                    v-model="data.categoryName"
                    class="input"
                    :disabled="isCheck"
                    maxlength="6"
                    placeholder="输入三级类别名称（最大6个字符）"
                  />
                  <el-upload
                    :headers="headers"
                    :data="dataObj"
                    :multiple="false"
                    :show-file-list="false"
                    :file-list="data.categoryImgArray"
                    :on-success="handleImageSuccess"
                    class="upload-uploader"
                    :action="action"
                  >
                    <img
                      v-if="data.categoryImgArray && data.categoryImgArray[0].url"
                      width="80"
                      height="80"
                      :src="data.categoryImgArray && data.categoryImgArray[0].url"
                    />
                    <el-icon v-else>
                      <el-icon-plus />
                    </el-icon>
                  </el-upload>
                </div>
              </template>
            </div>
            <div
              v-if="!isCheck"
              class="setting-box"
            >
              <el-button
                type="primary"
                link
                @click="() => append(data)"
              >{{ addTips(data.depth) }}
              </el-button>
              <el-button
                type="primary"
                link
                v-if="data.depth > 1"
                @click="() => remove(node, data)"
              >删除
              </el-button>
            </div>
          </div>
        </template>
      </el-tree>
      <div class="add-btn-wrap">
        <template v-if="isCheck">
          <el-button
            class="add"
            type="primary"
            @click="close"
          >确定
          </el-button>
        </template>
        <template v-else>
          <el-button
            v-if="type === 'add'"
            class="add"
            type="primary"
            @click="addClassification"
          >添加一级类别名称
          </el-button>
          <el-button
            type="primary"
            @click="onSubmit"
          >保存
          </el-button>
        </template>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { Plus as ElIconPlus } from '@element-plus/icons-vue'
// 移除未使用的uploadUrl导入
import { addCommodityClass, getCommodityClassById, updateCommodityClass } from '@/api/commodityClassApi'
import { computed, getCurrentInstance, ref, toRefs, watch } from 'vue';
import { ElMessage } from 'element-plus'

// 定义暴露的方法

let idx = 1000
let imgId = 1
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  type: {
    type: String,
    default: 'add'
  },
  params: {
    type: Object,
    default: () => ({})
  }
})

const { dialogVisible, type } = toRefs(props)
const params = ref({
  categoryName: '',
})
const file = ref('')
const imgList = ref([])
const customParams = ref({
  current: 1,
  map: {},
  model: {
    config: '',
    isCustom: true,
    isDelete: 0,
    name: '',
  },
  order: 'descending',
  size: 100,
  sort: 'id',
})
const treeData = ref([])
const headers = ref({
  Authorization: '',
})
const isSubmitting = ref(false) // 防止重复提交的状态变量
const action = ref('') // 图片上传地址需要配置

// 监听params变化，自动调用setParams
watch(() => props.params, (newParams) => {
  if (newParams && Object.keys(newParams).length > 0) {
    setParams(newParams) // 直接传递参数，不要包装成categoryData
  }
}, { immediate: true })

const dataObj = ref({
  folderId: 1,
})
const deleteArr = ref([])

const visible = computed({
  get () {
    return dialogVisible.value
  },
  set (val) {
    if (!val) {
      handleClose()
    }
    // 确保值变化时通知父组件
    emit('update:dialogVisible', val)
  }
})
const title = computed(() => {
  const stateMap = {
    add: '编辑类别',
    edit: '编辑类别',
    check: '编辑类别',
  }
  return stateMap[type.value]
})
const isCheck = computed(() => {
  return type.value === 'check'
});

// 分类数据处理函数已整合到setParams中

function handleImageSuccess (response, file, fileList) {
  const url = response.data.url
  fileList[0].url = url
}

function handleImageSuccessOne (response, file, fileList) {
  const url = response.data.url
  fileList[0].imgPath = url
}

const emit = defineEmits(['close', 'success', 'update:visible', 'update:dialogVisible'])

function handleClose () {
    console.log('弹窗关闭处理中');
    deleteArr.value = []
    isSubmitting.value = false // 重置提交状态，确保下次可以正常提交
  // 清除分类数据，避免下次打开时显示之前的数据
  treeData.value = []
  emit('close')
  }

function reset () {
  treeData.value = []
}

function addClassification () {
  treeData.value.push({
    placeholder: '输入一级类别名称',
    addTips: '添加二级类别名称',
    categoryName: '',
    categoryPath: '',
    depth: 1,
    idx: idx++,
    categoryImgArray: [
      {
        id: imgId++,
        imgPath: '',
      },
    ],
  })
}

function append (data) {
  const { categoryName } = data
  const depth = data.depth + 1
  let newChild
  if (!data.childs) {
    data.childs = []
  }
  if (depth < 3) {
    newChild = {
      placeholder: '输入二级类别名称',
      addTips: '添加三级类别名称',
      depth,
      parentName: categoryName,
      categoryName: '',
      categoryPath: '',
      categoryImgArray: [
        {
          id: imgId++,
          imgPath: '',
        },
      ],
      childs: [],
      idx: idx++,
    }
  } else {
    newChild = {
      parentName: categoryName,
      categoryImgArray: [
        {
          id: imgId++,
          url: '',
        },
      ],
      depth: 3,
      categoryName: '',
      idx: idx++,
    }
  }
  data.childs.push(newChild)
  treeData.value = JSON.parse(JSON.stringify(treeData.value))
}

const elTreeRef = ref();
// 已存在deleteArr变量用于跟踪删除的分类ID
function remove (node, data) {
  const parent = node.parent
  const children = parent.data.childs || parent.data
  const index = children.findIndex((d) => d.idx === data.idx)
  if (index !== -1) {
    deleteArr.value.push(data.id || '')
    elTreeRef.value.remove(node)
  } else {
    ElMessage.warning('数据错误，请重试')
  }
}

function onSubmit () {
  console.log(type)
  if (type.value === 'add') {
    addGroup()
  } else {
    updateGroup()
  }
}

// 构建符合后端要求的分类数据结构 - 保留树形结构
function buildClassifyData(item) {
  const {
    categoryName,
    categoryImgArray,
    categoryPath,
    parentName,
    depth,
    id,
    link,
  } = item

  const newMap = {
    depth: depth,
    categoryName,
    categoryPath: categoryPath || '',
    parentName,
    link: link || null,
    id,
  }

  // 处理图片 - 根据不同层级使用不同字段
  if (categoryImgArray) {
    if (depth < 3) {
      newMap.categoryImg = categoryImgArray[0]?.imgPath || categoryImgArray[0]?.url
    } else {
      newMap.categoryImg = categoryImgArray[0]?.url || categoryImgArray[0]?.imgPath
    }
  }

  // 验证图片是否存在
  if (!newMap.categoryImg) {
    ElMessage.error('分类"' + categoryName + '"请上传分类图片')
    throw new Error('未上传分类图片')
  }

  // 递归处理子级分类 - 保留树形结构
  if (item.childs && Array.isArray(item.childs) && item.childs.length > 0) {
    // 过滤有效子级
    const validChilds = item.childs.filter(child =>
      child &&
      child.categoryName &&
      child.categoryName.trim() !== ''
    )

    // 递归构建子级数据
    if (validChilds.length > 0) {
      newMap.childs = validChilds.map(buildClassifyData)
    }
  }

  return newMap
}

// 检查分类数据完整性
function checkCategories(categories) {
  for (let i = 0; i < categories.length; i++) {
    const parentCategory = categories[i];
    if (parentCategory.childs && parentCategory.childs.length > 0) {
      for (let j = 0; j < parentCategory.childs.length; j++) {
        let hasSecondLevelCategory = false;
        let hasThirdLevelCategory = false;
        const childCategory = parentCategory.childs[j];
        if (childCategory.depth === 2) {
          hasSecondLevelCategory = true;
          if (childCategory.childs && childCategory.childs.length > 0) {
            hasThirdLevelCategory = true;
          }
        }
        if (!hasSecondLevelCategory || !hasThirdLevelCategory) {
          ElMessage.error(`请在${childCategory.categoryName}分类下添加三级类别!`)
          return false;
        }
      }
    } else {
      ElMessage.error(`请在${parentCategory.categoryName}分类下添加二级类别!`)
      return false;
    }
  }
  return true;
}

// 批量保存分类数据 - 符合后端API要求的实现
async function saveCategory(classifies, deleteIds = []) {
  console.log('开始批量保存分类数据...')
  console.log('分类数据:', JSON.stringify(classifies))
  console.log('删除ID数组:', deleteIds)

  // 构建符合后端要求的请求参数
  const requestData = {
    classifies: classifies,
    deleteIds: deleteIds
  }

  try {
    let res

    // 根据是否包含ID判断是新增还是更新
    const hasExistingClass = classifies.some(cls => cls.id)

    if (hasExistingClass) {
      // 更新模式
      console.log('调用更新接口:', requestData)
      // 这里需要使用正确的API接口 - 根据实际情况调整
      res = await updateCommodityClass(requestData)
    } else {
      // 新增模式
      console.log('调用新增接口:', requestData)
      // 这里需要使用正确的API接口 - 根据实际情况调整
      res = await addCommodityClass(requestData)
    }

    // 检查响应
    const isSuccess = res && (res.code === '200' || res.code === 200 || res.code === '' || res.code === true)
    if (!isSuccess) {
      throw new Error(res.message || '保存失败')
    }

    console.log('批量保存成功:', res)
    return res
  } catch (error) {
    console.error('批量保存失败:', error)
    throw new Error(error.message || '保存失败')
  }
}

// 添加分类组
async function addGroup() {
  // 防止重复提交检查
  if (isSubmitting.value) {
    console.log('检测到重复提交，已阻止')
    return
  }
  isSubmitting.value = true

  try {
    // 构建分类数据结构 - 保持树形结构
    console.log('开始构建分类数据结构...')

    // 过滤有效数据并构建树形结构
    const validTreeData = treeData.value.filter(item => item && item.categoryName && item.categoryName.trim() !== '')
    if (validTreeData.length === 0) {
      ElMessage.error('请添加分类')
      isSubmitting.value = false
      return
    }

    // 构建符合后端要求的数据结构
    const classifies = validTreeData.map(buildClassifyData)
    console.log('构建的分类数据:', JSON.stringify(classifies))

    // 检查分类完整性
    const isComplete = checkCategories(classifies)
    if (!isComplete) {
      isSubmitting.value = false
      return
    }

    // 保存分类数据
    console.log('开始保存分类数据...')
    await saveCategory(classifies, []) // 新增模式没有删除的ID

    console.log('所有分类保存成功')
    ElMessage.success('新增成功')

    // 触发成功事件
    emit('success')

    // 清理删除数组
    deleteArr.value = []

    // 延迟关闭弹窗确保异步操作完成
    setTimeout(() => {
      visible.value = false
    }, 500)
  } catch (error) {
    console.error('保存分类失败:', error)
    ElMessage.error(error.message || '保存失败')
  } finally {
    console.log('addGroup函数执行完成，重置提交状态')
    isSubmitting.value = false // 无论成功失败都重置提交状态
  }
}

// 更新分类组
async function updateGroup() {
  // 防止重复提交检查
  if (isSubmitting.value) {
    console.log('检测到重复提交，已阻止')
    return
  }
  isSubmitting.value = true

  try {
    // 构建分类数据结构 - 保持树形结构
    console.log('开始构建分类数据结构...')

    // 过滤有效数据并构建树形结构
    const validTreeData = treeData.value.filter(item => item && item.categoryName && item.categoryName.trim() !== '')
    if (validTreeData.length === 0) {
      ElMessage.error('请添加分类')
      isSubmitting.value = false
      return
    }

    // 构建符合后端要求的数据结构
    const classifies = validTreeData.map(buildClassifyData)
    console.log('构建的分类数据:', JSON.stringify(classifies))

    // 检查分类完整性
    const isComplete = checkCategories(classifies)
    if (!isComplete) {
      isSubmitting.value = false
      return
    }

    // 收集需要删除的分类ID并过滤无效ID
    const deleteIds = (deleteArr.value || []).filter(id => id && id !== '')
    console.log('需要删除的分类ID:', deleteIds)

    // 保存分类数据
    console.log('开始更新分类数据...')
    await saveCategory(classifies, deleteIds)

    console.log('所有分类更新成功')
    ElMessage.success('更新成功')

    // 触发成功事件
    emit('success')

    // 清理删除数组
    deleteArr.value = []

    // 延迟关闭弹窗确保异步操作完成
    setTimeout(() => {
      visible.value = false
    }, 500)
  } catch (error) {
    console.error('更新分类失败:', error)
    ElMessage.error(error.message || '更新失败')
  } finally {
    console.log('updateGroup函数执行完成，重置提交状态')
    isSubmitting.value = false // 无论成功失败都重置提交状态
  }
}

// 递归处理分类数据为树形结构
function processCategoryData(data, depth = 1) {
  // 调试日志，查看数据结构
  console.log(`Processing data at depth ${depth}:`, data);

  const processed = {
    id: data.classifyId || data.id,
    categoryName: data.classifyName || data.categoryName,
    parentName: data.parentName || '',
    depth: depth,
    categoryImgArray: data.categoryImg ? [{ imgPath: data.categoryImg, url: data.categoryImg }] : [],
    oneClassifyId: data.oneClassifyId || '',
    childs: [] // 使用childs字段，与el-tree组件的props配置匹配
  }

  // 处理子级分类 - 检查所有可能的子级字段名
  if (data.childs && Array.isArray(data.childs) && data.childs.length > 0) {
    console.log(`Found childs at depth ${depth}:`, data.childs);
    processed.childs = data.childs.map(child => processCategoryData(child, depth + 1))
  } else if (data.children && Array.isArray(data.children) && data.children.length > 0) {
    console.log(`Found children at depth ${depth}:`, data.children);
    processed.childs = data.children.map(child => processCategoryData(child, depth + 1))
  } else if (data.child && Array.isArray(data.child) && data.child.length > 0) {
    console.log(`Found child at depth ${depth}:`, data.child);
    processed.childs = data.child.map(child => processCategoryData(child, depth + 1))
  } else {
    console.log(`No children found at depth ${depth}`);
  }

  return processed
}

async function setParams (params) {
  try {
    console.log('Received params in setParams:', params);

    // 如果有id参数，说明是编辑/查看模式
    if (params && params.id) {
      console.log('Fetching details for id:', params.id);
      // 根据id查询详情
      const res = await getCommodityClassById({ oneClassifyId: params.id })
      console.log('API response:', res);

      if (res && res.data) {
        // 处理响应数据，兼容不同字段名
        const data = res.data
        console.log('Processing data:', data);
        console.log('Is data array:', Array.isArray(data));

        // 尝试直接使用原始数据结构（可能已经是树形结构）
        if (Array.isArray(data)) {
          // 如果返回的是数组，处理每个分类
          console.log('Processing as array with length:', data.length);
          treeData.value = data.map(item => processCategoryData(item, 1))
        } else {
          // 如果返回的是单个对象
          console.log('Processing as single object');
          treeData.value = [processCategoryData(data, 1)]
        }

        console.log('Final treeData:', treeData.value);
        // 检查是否有子级数据
        treeData.value.forEach((item, index) => {
          console.log(`Root item ${index} has childs:`, item.childs && item.childs.length > 0,
                     'with count:', item.childs ? item.childs.length : 0);
          // 检查第一层子级
          if (item.childs && item.childs.length > 0) {
            item.childs.forEach((child, childIndex) => {
              console.log(`  Child ${childIndex}:`, child.categoryName);
            });
          }
        });
      }
    } else if (params && params.treeData) {
      // 如果是新增模式且有预设的树形数据
      console.log('Using provided treeData:', params.treeData);
      treeData.value = JSON.parse(JSON.stringify(params.treeData))
    } else {
      // 新增模式，初始化空数据
      console.log('Initializing empty data');
      treeData.value = [{
        id: '',
        categoryName: '',
        parentName: '',
        depth: 1,
        categoryImgArray: []
      }]
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')

    // 出错时初始化空数据
    treeData.value = [{
      id: '',
      categoryName: '',
      parentName: '',
      depth: 1,
      categoryImgArray: []
    }]
  }
}

// 暴露方法给父组件
defineExpose({ setParams })

function addTips (depth) {
  depth = depth + ''
  const tipsMp = {
    1: '添加二级类别名称',
    2: '添加三级类别名称',
  }
  return tipsMp[depth]
}

function placeholderTips (depth) {
  depth = depth + ''
  const tipsMp = {
    1: '输入一级类别名称（最大6个字符）',
    2: '输入二级类别名称（最大6个字符）',
  }
  return tipsMp[depth]
}

// 判断是否存在三级类别
// 简化的验证逻辑已整合到addGroup和updateGroup函数中
</script>

<style lang="scss">
.add-dialog-component {
  .tree-box {
    .el-tree-node__content {
      margin-bottom: 15px;
      height: auto;
    }
  }
}
</style>

<style lang="scss" scoped>
.group-dialog {
  .el-dialog {
    min-width: 500px;
    max-width: 600px;
  }
}

.add-dialog-component {
  padding: 15px 20px;
  max-height: 60vh;
  overflow: auto;

  .el-tree-node__content {
    &:hover {
      background-color: #fff;
    }
  }

  .tree-box {
    margin: 15px 0;

    .custom-tree-node {
      display: flex;
      width: 100%;
      text-align: left;

      .content {
        flex: 1;
        display: flex;
        align-items: center;

        .input {
          width: 60%;
          margin-right: 20px;
        }

        .textarea-input {
          width: 100%;
          margin-left: 15px;

          textarea {
            height: 80px;
          }
        }
      }

      .level-3-wrap {
        display: flex;
        width: 300px;

        .upload-wrap {
          position: relative;

          &.disabled::after {
            content: '';
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            z-index: 999;
            background-color: #f5f7fa;
            opacity: 0.5;
          }

          .el-upload {
            border: 1px dashed #d9d9d9;
          }

          i {
          }

          img {
            width: 80px;
            height: 80px;
          }
        }
      }
    }
  }

  .add-btn-wrap {
    text-align: center;
  }
}

.upload-uploader {
  margin-left: 30px;
}
</style>
